#include "RedisClient.h"

void RedisClient::disconnect() {  
    if (context_) {  
        redisFree(context_);  
        context_ = nullptr;  
    }  
}  

void RedisClient::connect() {  
    context_ = redisConnect(host_.c_str(), port_);  
    if (context_ == nullptr || context_->err) {  
        if (context_) {  
            std::cerr << "Connection error: " << context_->errstr << std::endl;  
            redisFree(context_);  
            context_ = nullptr;  
        } else {  
            std::cerr << "Connection error: can't allocate redis context" << std::endl;  
    }
        throw std::runtime_error("Failed to connect to Redis");  
    }
    //login password
    redisCommand(context_, "AUTH 123");    
}  

std::string RedisClient::sendCommand(const std::string& command) {  
    redisReply* reply = static_cast<redisReply*>(redisCommand(context_, command.c_str()));  
    if (reply == nullptr) {  
        throw std::runtime_error("Failed to send command to Redis");  
    }  
  
    std::string result;  
    switch (reply->type) {  
        case REDIS_REPLY_STRING:  
            result = reply->str;  
            break;  
        case REDIS_REPLY_INTEGER:  
            result = std::to_string(reply->integer);  
            break;  
        case REDIS_REPLY_NIL:  
            result = "nil";  
            break;  
        case REDIS_REPLY_STATUS:  
            result = reply->str;  
            break;  
        case REDIS_REPLY_ARRAY:  
        case REDIS_REPLY_ERROR:  
        default:   
            throw std::runtime_error("Unsupported reply type");  
    }  

    freeReplyObject(reply);  
    return result;  
}  